--桌子逻辑
local skynet = require "skynet"
local cluster = require "skynet.cluster"
local tabletool = require "tabletool"
local timetool = require "timetool"
local timer = require "timer"
local filelog = require "filelog"
local configdao = require "configdao"
local json = require "cjson"
json.encode_sparse_array(true, 1, 1)

require "lhjenum"

local TableLogic = {}
local service = nil
local seatlogic = nil
local gamelogic = nil

function TableLogic.init(caller)
	service = caller
end

-- 在tablecmd:start 调用的
-- 这里的 tableobj，其实就是 table_data
-- conf 是从客户端传上来的, table_conf
--
function TableLogic.init_data(tableobj, conf, attachconf)
	-- 这里的两个logic 是tablelogic后面才加入进去的，所以没办法放到 init() 里面去初始化
	seatlogic = service:get_logicbyname("seatlogic")

	-- 获得游戏逻辑
	gamelogic = service:get_logicbyname("gamelogic")
	if conf == nil  then
		filelog.sys_error("TableLogic.init_data conf == nil", conf)
		return false
	end

    --初始化桌子信息
	local now = timetool.get_time()
    local nodename = skynet.getenv("nodename")
	tableobj.table_type = conf.table_type
	tableobj.uuid = nodename .. "_" .. attachconf.code .. "_" .. attachconf.index .. "_" .. now
	tableobj.index = attachconf.index
	tableobj.code = attachconf.code
	tableobj.state = ELHJTableState.TABLE_STATE_WAIT_PLAYER_SITDOWN
	tableobj.create_rid = attachconf.rid
	tableobj.create_rolename = attachconf.rolename
    tableobj.create_logo = attachconf.logo
	tableobj.create_time = now
	tableobj.cur_player_num = 0
	tableobj.curr_to_num = 0
	tableobj.conf = conf
    tableobj.cur_watch_playernum = 0
    tableobj.table_service = attachconf.table_service
    tableobj.sitdown_player_num = 0
    tableobj.agencylevel = attachconf.agencylevel            --代理等级，0表示非代理创建桌
    tableobj.table_persist = attachconf.table_persist        --桌子没人时，保留时间
    tableobj.tradeid = attachconf.tradeid
    tableobj.last_heart_time = now
    tableobj.level_type = attachconf.level_type or 1

    --设置最小携带量
    if not tableobj.conf.min_carry_amount or tableobj.conf.min_carry_amount < 0 then
        tableobj.conf.min_carry_amount = 0
    end

    --设置最大携带量
    if not tableobj.conf.max_carry_amount or tableobj.conf.max_carry_amount < 0 then
        tableobj.conf.max_carry_amount = 0
    end

    --设置最大玩家数
    tableobj.conf.max_player_num = tableobj.conf.max_player_num or 1

    --初始化倍率列表
    tableobj.odds_list = {}
    for _,v in pairs(tableobj.conf.odds_list) do
        local id = math.floor(v / 10000)
        local odds = v % 10000
        tableobj.odds_list[id] = odds
    end

    --初始化桌子奖池
    local gamename = TableLogic.get_gamename(tableobj)
    local jackpot_id,jackpot_money = skynet.call(".jackpotmgr", "lua", "init_table_jackpot", gamename, tableobj.level_type, tableobj.table_service)
    tableobj.cur_jackpot_id = jackpot_id or 0
    tableobj.cur_jackpot_money = jackpot_money or 0

    local jackpot_timer = skynet.call(".jackpotmgr", "lua", "get_jacpot_timer", gamename, jackpot_id)
    if jackpot_timer then
        tableobj.open_jackpot_timestamp = jackpot_timer.outtime
        tableobj.open_jackpot_countdown = jackpot_timer.delaytime
    end

    --添加座位
	local seat
	local count = 1
	while count <= conf.max_player_num do
		seat = { }
        seatlogic.init_data(seat,count)
		table.insert(tableobj.seats, seat) --初始化座位数据
		count = count + 1
	end

    --初始游戏数据
	tableobj.gameobj = {tableobj = {}, stateevent = {}}
	gamelogic.init_data(tableobj.gameobj, tableobj)

	gamelogic.wait_player_sitdown(tableobj.gameobj)

	return true
end

---------------------------------------------------------
--处理客户端请求
--

--
-- 进桌
-- 客户端进桌请求最终在这里处理
-- tableobj：桌子对象
-- request：请求包
-- seat： 座位对象，nil or 非nil，由此判断是否重进桌子？
--
function TableLogic.entertable(tableobj, rid, roledata, request, seat)
    local playerinfo = roledata.info or {}
    local playermoney = roledata.money or {}

    --处理重进桌子
	if seat then
		local noticemsg = {
			rid = seat.rid,
			seat_index = seat.index,	
		}
		TableLogic.sendmsg_to_tableplayer(seat.rid,"reentertableN", noticemsg)
		if not tableobj.is_had_start then
			if tableobj.delete_table_timer_id > 0 then
				timer.cleartimer(tableobj.delete_table_timer_id)
				tableobj.delete_table_timer_id = -1
			end
		end
	else    --新进入桌子

        --先加入等待玩家列表，并设置相关信息
		local waitinfo = tableobj.waits[rid]
        if waitinfo == nil then
			waitinfo = {}
			waitinfo.playerinfo = {}
			tableobj.waits[rid] = waitinfo
			tableobj.cur_watch_playernum = tableobj.cur_watch_playernum + 1			 
        end

		waitinfo.rid = rid
        waitinfo.playerinfo.coin = playermoney.coin
        waitinfo.playerinfo.diamond = playermoney.diamond
        waitinfo.is_robot = roledata.is_robot
        --暂不支持旁观，超过10s未坐下，则踢出
        if not waitinfo.watch_timer_id then
            waitinfo.watch_timer_id = 0
            local curmoney = TableLogic.get_curmoney(waitinfo)
            waitinfo.watch_timer_id = timer.settimer(10 * 100,"do_watch",{rid = rid, coin = curmoney})
        end
	end

    --如果正在删除桌子，停止删除
	if tableobj.delete_table_timer_id > 0 then
		timer.cleartimer(tableobj.delete_table_timer_id)
		tableobj.delete_table_timer_id = -1
	end

    if tableobj.sitdown_player_num <= 0 then
        tableobj.state = ELHJTableState.TABLE_STATE_WAIT_PLAYER_SITDOWN
    end
end

--
--坐下
--
function TableLogic.sitdowntable(tableobj, rid, request, seat,roledata)
    local playerinfo = roledata.info or {}
    local playermoney = roledata.money or {}

    --清空旁观超时计时器
    local waitinfo = tableobj.waits[rid] or {}
    if waitinfo.watch_timer_id and waitinfo.watch_timer_id > 0 then
        timer.cleartimer(waitinfo.watch_timer_id)
    end
    tableobj.waits[rid] = nil
    tableobj.cur_watch_playernum = tableobj.cur_watch_playernum - 1

    --初始化seat数据
	seat.rid = rid
	seat.playerinfo.rolename = playerinfo.rolename or ""
	seat.playerinfo.logo = playerinfo.logo or ""
	seat.playerinfo.sex = playerinfo.sex or 0
	seat.playerinfo.ip_addr = roledata.ip_addr or playerinfo.ip_addr
    seat.playerinfo.gps_addr = roledata.gps_addr or playerinfo.gps_addr
    seat.playerinfo.recommrid =  playerinfo.recommrid           --推荐人rid
	seat.playerinfo.agencyrid =  playerinfo.agencyrid           --代理rid
	seat.playerinfo.agencylevel =  playerinfo.agencylevel or 0  --代理等级，0表示不是代理
    seat.playerinfo.level = playerinfo.level or 0
    seat.playerinfo.intro = playerinfo.intro or ""
    seat.playerinfo.upvoted_num = playerinfo.upvoted_num
    seat.playerinfo.downvoted_num = playerinfo.downvoted_num
    seat.playerinfo.logoframe = playerinfo.logoframe

	seat.state = ELHJSeatState.SEAT_STATE_WAIT_READY
	seat.playerinfo.coin = playermoney.coin or 0
	seat.playerinfo.lock_coin = playermoney.lock_coin or 0
	seat.playerinfo.diamond = playermoney.diamond or 0
    seat.playerinfo.lock_diamond = playermoney.lock_diamond or 0
	seat.is_disconnected = false
    seat.is_robot = roledata.is_robot or false
    seat.cur_base_score = tableobj.conf.base_score_list[1] --默认选择第1个可选底注
    seat.cur_multi_num = tableobj.conf.multi_num_list[1] --默认选择第1个可选倍数
    seat.cur_line_num = 9              --默认9线
    seat.cur_total_bet = seat.cur_multi_num * seat.cur_base_score * seat.cur_line_num

	tableobj.state = ELHJTableState.TABLE_STATE_WAIT_ALL_READY
	gamelogic.on_sitdown_table(tableobj.gameobj, seat)

    seat.ready_to_time = seat.ready_to_time or 1        --测试
    seat.ready_timeout_time = timetool.get_time() + seat.ready_to_time

    --设置超时
    if not seat.ready_timer_id or seat.ready_timer_id == -1 then
        seat.ready_timer_id = 0
        seat.ready_timer_id = timer.settimer(seat.ready_to_time * 5,"doready",{seat_index = seat.index,rid = seat.rid})
    end
end

--
--- 准备
-- @param tableobj 牌桌对象
-- @param request 请求数据
-- @param seat 桌位对象
--
function TableLogic.gameready(tableobj, request, seat, roledata)
	if tableobj.state ~= ELHJTableState.TABLE_STATE_WAIT_ALL_READY then
		return
	end

	local noticemsg = {
		rid = seat.rid,
		seat_index = seat.index,
		is_ready = false,
	}

	if seat.state == ELHJSeatState.SEAT_STATE_WAIT_START then 
		noticemsg.is_ready = true 
	end
	--TableLogic.sendmsg_to_alltableplayer(tableobj, "gamereadyN", noticemsg)

end

--
-- doaction操作
--
function TableLogic.doaction(tableobj, rid, request, seat)
	local action_type = request.action_type or 0

    local call_func = nil
    if action_type == ELHJActionType.ACTION_TYPE_START then                     --开始游戏
        call_func = TableLogic.start_game
    elseif action_type == ELHJActionType.ACTION_TYPE_INC_SCORE then             --增加底注
        call_func = TableLogic.change_score
    elseif action_type == ELHJActionType.ACTION_TYPE_DEC_SCORE then             --减少底注
        call_func = TableLogic.change_score
    elseif action_type == ELHJActionType.ACTION_TYPE_INC_LINE then              --增加线数
        call_func = TableLogic.change_line
    elseif action_type == ELHJActionType.ACTION_TYPE_FULL_LINE then             --切换到满线
        call_func = TableLogic.change_line
    elseif action_type == ELHJActionType.ACTION_TYPE_AUTO_START then            --自动开始
        call_func = TableLogic.auto_start
    elseif action_type == ELHJActionType.ACTION_TYPE_STOP_SPIN then             --停止旋转
        call_func = TableLogic.stop_spin
    elseif action_type == ELHJActionType.ACTION_TYPE_INC_MULTI then             --增加倍数
        call_func = TableLogic.change_multi
    elseif action_type == ELHJActionType.ACTION_TYPE_DEC_MULTI then             --减少倍数
        call_func = TableLogic.change_multi
    elseif action_type == ELHJActionType.ACTION_TYPE_COMPARE_MULTI then         --比倍  
        call_func = TableLogic.compare_multi
    elseif action_type == ELHJActionType.ACTION_TYPE_COLLECT_SCORE then         --收分
        call_func = TableLogic.collect_score
    elseif action_type == ELHJActionType.ACTION_TYPE_DO_BET then                --押注
        call_func = TableLogic.do_bet
    else
        return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "无效的操作类型"}
    end

    return call_func(tableobj, request, seat)
end

--
--开始游戏
--
function TableLogic.start_game(tableobj, request, seat)
    if tableobj.is_ingame then
        filelog.sys_info("------start game error----", tableobj.state, seat.rid)
        return {retcode = EErrCode.ERR_GAMING, retstr = "游戏已开始！"}
    end

    if tableobj.is_auto_start and tableobj.is_will_auto_start then
        return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "请先取消自动开始"}
    end

    --检测金币是否够
    local min_money = 1000    --低于10元不能开始
    local coin = TableLogic.get_curmoney(seat)
    if seat.cur_total_bet > coin or coin < min_money then
        return {retcode = EErrCode.ERR_NOT_ENOUGH_DIAMOND, retstr = "余额不足10，不能继续游戏"}
    end

    if tableobj.is_had_start then
        if TableLogic.is_canstartgame(tableobj) then
            tableobj.state = ELHJTableState.TABLE_STATE_ONE_GAME_START
            gamelogic.run(tableobj.gameobj)
        end
    else
        local isallready = true
        local playernum = 0
        for k, v in pairs(tableobj.seats) do
		    if not seatlogic.is_empty(v) then
			    if not v.had_ready then
				    isallready = false
				    break
			    end
			    playernum = playernum + 1
		    end
	    end

        if isallready and playernum >= tableobj.conf.max_player_num
        and tableobj.state == ELHJTableState.TABLE_STATE_WAIT_ALL_READY then		
			--当前不支持旁观，踢出旁观玩家
			local waits = tabletool.deepcopy(tableobj.waits)
			for rid, waitinfo in pairs(waits) do
				TableLogic.passive_leavetable(tableobj, rid, waitinfo.playerinfo.diamond)
			end

            tableobj.state = ELHJTableState.TABLE_STATE_GAME_START
		    gamelogic.run(tableobj.gameobj)
	    end
    end

    return {action_type = request.action_type}
end

--
--更改底注,切换到下一个或上一个可选底注
--
function TableLogic.change_score(tableobj, request, seat)
    local base_score_list = tableobj.conf.base_score_list
    local cur_score = seat.cur_base_score
    local action_type = request.action_type
    
    --游戏中
    if tableobj.is_ingame then
        return {retcode = EErrCode.ERR_GAMING, retstr = "游戏中不能操作"}
    end

    local is_inc = true
    if action_type == ELHJActionType.ACTION_TYPE_DEC_SCORE then
        is_inc = false
    end

    local new_score = nil
    for i,v in ipairs(base_score_list) do
        if v == cur_score then
            if is_inc then
                new_score = base_score_list[i+1]
            else
                new_score = base_score_list[i-1]
            end
            break
        end
    end

    --没找到，则返回第一个可选底注
    if not new_score then
        if is_inc then
            new_score = base_score_list[1]
        else
            local len = #base_score_list
            new_score = base_score_list[len]
        end
    end

    --检测是否超上限
    local money = TableLogic.get_curmoney(seat)
    local cur_total_bet = new_score * seat.cur_line_num * seat.cur_multi_num
    if cur_total_bet > money then
        return {retcode = EErrCode.ERR_NOT_ENOUGH_DIAMOND, retstr = "您的金币不够"}
    end
    seat.cur_base_score = new_score
    seat.cur_total_bet = cur_total_bet

    return {action_type = request.action_type, cur_base_score = new_score, cur_total_bet = cur_total_bet}
end

--
--更改倍数,切换到下一个或上一个可选倍数
--
function TableLogic.change_multi(tableobj, request, seat)
    local multi_num_list = tableobj.conf.multi_num_list
    local cur_multi = seat.cur_multi_num
    local action_type = request.action_type
    
    --游戏中
    if tableobj.is_ingame then
        return {retcode = EErrCode.ERR_GAMING, retstr = "游戏中不能操作"}
    end

    local is_inc = true
    if action_type == ELHJActionType.ACTION_TYPE_DEC_MULTI then
        is_inc = false
    end

    local new_multi = nil
    for i,v in ipairs(multi_num_list) do
        if v == cur_multi then
            if is_inc then
                new_multi = multi_num_list[i+1]
            else
                new_multi = multi_num_list[i-1]
            end
            break
        end
    end

    --没找到，则返回第一个可选倍数
    if not new_multi then
        if is_inc then
            new_multi = multi_num_list[1]
        else
            local len = #multi_num_list
            new_multi = multi_num_list[len]
        end
    end

    --检测是否超上限
    local money = TableLogic.get_curmoney(seat)
    local cur_total_bet = new_multi * seat.cur_line_num * seat.cur_base_score
    if cur_total_bet > money then
        return {retcode = EErrCode.ERR_NOT_ENOUGH_DIAMOND, retstr = "您的金币不够"}
    end
    seat.cur_multi_num = new_multi
    seat.cur_total_bet = cur_total_bet

    return {action_type = request.action_type, cur_multi_num = new_multi, cur_total_bet = cur_total_bet}
end

--
--更改线数,增加到下一线或切换到满线
--
function TableLogic.change_line(tableobj, request, seat)
    local max_line_num = tableobj.max_line_num
    local cur_line_num = seat.cur_line_num
    
    --游戏中
    if tableobj.is_ingame then
        return {retcode = EErrCode.ERR_GAMING, retstr = "游戏中不能操作"}
    end

    --满线
    if request.action_type == ELHJActionType.ACTION_TYPE_FULL_LINE then
        cur_line_num = max_line_num
    else
        cur_line_num = cur_line_num + 1
        if cur_line_num > max_line_num then
            cur_line_num = 1
        end
    end

    --检测是否超上限
    local money = TableLogic.get_curmoney(seat)
    local cur_total_bet = cur_line_num * seat.cur_base_score * seat.cur_multi_num
    if cur_total_bet > money then
        return {retcode = EErrCode.ERR_NOT_ENOUGH_DIAMOND, retstr = "您的金币不够"}
    end
    seat.cur_line_num = cur_line_num
    seat.cur_total_bet = cur_total_bet

    return {action_type = request.action_type, cur_line_num = cur_line_num, cur_total_bet = cur_total_bet}
end

--
--设置是否自动开始游戏
--当前为非自动，则切换为自动；当前为自动则切换为非自动
--
function TableLogic.auto_start(tableobj, request, seat)
    if tableobj.is_auto_start then
        tableobj.is_auto_start = false
    else
        --tableobj.is_auto_start = true
    end

    return {action_type = request.action_type, is_auto_start = tableobj.is_auto_start}
end

--
--停止旋转动画，立即显示结果
--
function TableLogic.stop_spin(tableobj, request, seat)
    if tableobj.state == ELHJTableState.TABLE_STATE_WAIT_HANDLE_SPIN_RESULT then
        if tableobj.timer_id > 0 then
            timer.cleartimer(tableobj.timer_id)
            tableobj.timer_id = -1
        end

        --立即处理转动结果
        tableobj.state = ELHJTableState.TABLE_STATE_HANDLE_SPIN_RESULT
	    gamelogic.run(tableobj.gameobj)	
    end

    return {action_type = request.action_type}
end

--
--比倍
--
function TableLogic.compare_multi(tableobj, request, seat)

    --当前不能比倍
    if not tableobj.is_wait_comp_multi then
        return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "错误的操作类型！"}
    end
    
    --已经在比倍中
    if tableobj.is_compare_multiing then
        return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "已经在比倍中！"}
    end
    
    --取消定时器
    if tableobj.timer_id > 0 then
        timer.cleartimer(tableobj.timer_id)
        tableobj.timer_id = -1
    end
    
    --等待玩家下注
    tableobj.state = ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_END
    local timer_id = timer.settimer(2500, "onegameend")	
    if tableobj.state ~= ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_END then
        timer.cleartimer(timer_id)
    else
        tableobj.timer_id = timer_id
    end
    
    local now = timetool.get_time()
    tableobj.is_compare_multiing = true
    tableobj.is_wait_comp_multi = false
    tableobj.action_timeout_time = now + (tableobj.do_bet_timeout or 21)
    
    --通知押注
    local noticemsg = {
        wait_action_type = ELHJActionType.ACTION_TYPE_DO_BET,
        action_timeout_time = tableobj.action_timeout_time - 1,
    }
    TableLogic.sendmsg_to_alltableplayer(tableobj, "todoN", noticemsg)
    
    return {action_type = request.action_type}
end

--
--收分
--
function TableLogic.collect_score(tableobj, request, seat)

    --当前不能收分
    if not tableobj.is_wait_comp_multi 
    and not tableobj.is_compare_multiing then
        return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "错误的操作类型！"}
    end
    tableobj.is_wait_comp_multi = nil
    tableobj.is_compare_multiing = nil
    
    --取消定时器
    if tableobj.timer_id > 0 then
        timer.cleartimer(tableobj.timer_id)
        tableobj.timer_id = -1
    end
    
    --结束游戏
    tableobj.state = ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_END
    local timer_id = timer.settimer(5, "onegameend")	
    if tableobj.state ~= ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_END then
        timer.cleartimer(timer_id)
    else
        tableobj.timer_id = timer_id
    end

    return {action_type = request.action_type}
end

--
--押注
--
function TableLogic.do_bet(tableobj, request, seat)

    --当前不能操作
    if not tableobj.is_compare_multiing then
        return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "当前不能操作！"}
    end
    
    local bet_item_id = request.bet_item_id or 0
    if bet_item_id < ELHJBetBtnId.BET_BTN_ID_LARGE 
    or bet_item_id > ELHJBetBtnId.BET_BTN_ID_TIE then
        return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "无效的参数"}
    end
    
    --取消定时器
    if tableobj.timer_id > 0 then
        timer.cleartimer(tableobj.timer_id)
        tableobj.timer_id = -1
    end
    
    --处理下注
    tableobj.cur_bet_item_id = bet_item_id
    gamelogic.handle_dobet(tableobj.gameobj)
    
    --比倍未结束则再次通知下注
    if tableobj.is_compare_multiing and tableobj.cur_total_score > 0 then
        local now = timetool.get_time()
        tableobj.action_timeout_time = now + (tableobj.do_bet_timeout or 21)
        
        --通知押注
        local noticemsg = {
            wait_action_type = ELHJActionType.ACTION_TYPE_DO_BET,
            action_timeout_time = tableobj.action_timeout_time - 1,
        }
        TableLogic.sendmsg_to_alltableplayer(tableobj, "todoN", noticemsg)
    end
    
    return {action_type = request.action_type}
end

--
--快速结束游戏
--
function TableLogic.quick_endgame(tableobj, request, seat)
    if tableobj.state == ELHJTableState.TABLE_STATE_WAIT_DO_SPIN then
        tableobj.state = ELHJTableState.TABLE_STATE_DO_SPIN
    elseif tableobj.state == ELHJTableState.TABLE_STATE_WAIT_HANDLE_SPIN_RESULT then
        tableobj.state = ELHJTableState.TABLE_STATE_HANDLE_SPIN_RESULT
    elseif tableobj.state == ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_END then
        tableobj.state = ELHJTableState.TABLE_STATE_ONE_GAME_END
    elseif tableobj.state == ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_REAL_END then
        tableobj.state = ELHJTableState.TABLE_STATE_ONE_GAME_REAL_END
    elseif tableobj.state == ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_START and tableobj.is_ingame then
        tableobj.is_ingame = false
        tableobj.is_onegameend = true
    elseif tableobj.is_ingame then
        skynet.sleep(50)
        if tableobj.is_ingame then
            filelog.sys_error("------table state is error------", tableobj.state)
            tableobj.is_ingame = false
        end
        return
    end

    if tableobj.timer_id > 0 then
        timer.cleartimer(tableobj.timer_id)
        tableobj.timer_id = -1
    end

    --立即处理
	gamelogic.run(tableobj.gameobj)	
end

--
--主动离桌
--
function TableLogic.leavetable(tableobj, request, rid, coin)
    local leavetablemsg = {
        rid = rid,
		table_index = tableobj.index,
	}

    if tableobj.waits[rid] ~= nil then
		TableLogic.sendmsg_to_alltableplayer(tableobj, "leavetableN", leavetablemsg)
		tableobj.cur_watch_playernum = tableobj.cur_watch_playernum - 1
        --通知router,删除rid-table的映射,并通知gate
        if not tableobj.waits[rid].is_robot then
            skynet.send(".router","lua","leave_table",nil,rid,tableobj.index,coin)
        end
	end
    tableobj.waits[rid] = nil

    --桌子正在删除直接返回
	if tableobj.isdeleting then
		return
	end

    --重置桌子数据
    if tableobj.is_had_start then
        gamelogic.reset_tabledata(tableobj.gameobj)
    end

	if tableobj.is_had_start then
		if tableobj.sitdown_player_num <= 0 then
            --删除定时器
            if tableobj.timer_id and tableobj.timer_id > 0 then
                timer.cleartimer(tableobj.timer_id)
                tableobj.timer_id = -1
            end
			if tableobj.delete_table_timer_id > 0 then
				timer.cleartimer(tableobj.delete_table_timer_id)
				tableobj.delete_table_timer_id = -1
			end
			if tableobj.delete_table_timer_id == -1 then
                tableobj.delete_table_timer_id = 0
                tableobj.delete_table_timer_id = timer.settimer(100, "delete_table")
            end
		end
	else
		if tableobj.sitdown_player_num <= 0 and tableobj.cur_watch_playernum <= 0 then
            --删除定时器
            if tableobj.timer_id and tableobj.timer_id > 0 then
                timer.cleartimer(tableobj.timer_id)
                tableobj.timer_id = -1
            end
			if tableobj.delete_table_timer_id > 0 then
				timer.cleartimer(tableobj.delete_table_timer_id)
				tableobj.delete_table_timer_id = -1
			end
			if tableobj.delete_table_timer_id == -1 then
                tableobj.delete_table_timer_id = 0
                tableobj.delete_table_timer_id = timer.settimer(100, "delete_table")
            end
		end
	end
end

--
--- 被动离桌
-- @param tableobj
-- @param rid
-- @param is_leave
--被动离开桌子，使用该接口时玩家必须是在旁观中
--记住使用者如果循环遍历旁观队列一定要使用原队列的copy队列
--
function TableLogic.passive_leavetable(tableobj, rid, coin, is_leave)
	local leavetablemsg = {
        rid = rid,
		table_index = tableobj.index,
	}

	if tableobj.waits[rid] ~= nil then
		TableLogic.sendmsg_to_alltableplayer(tableobj, "leavetableN", leavetablemsg)
		tableobj.cur_watch_playernum = tableobj.cur_watch_playernum - 1
        --通知router,删除rid-table的映射,并通知gate
        if not is_leave and not tableobj.waits[rid].is_robot then
            skynet.send(".router","lua","leave_table",nil,rid,tableobj.index,coin)
        end
	end
	tableobj.waits[rid] = nil

    --桌子正在删除直接返回
	if tableobj.isdeleting then
		return
	end

    --重置桌子数据
    if tableobj.is_had_start then
        gamelogic.reset_tabledata(tableobj.gameobj)
    end

    --游戏已经开始
	if tableobj.is_had_start then
		if tableobj.sitdown_player_num <= 0 then
            --删除定时器
            if tableobj.timer_id and tableobj.timer_id > 0 then
                timer.cleartimer(tableobj.timer_id)
                tableobj.timer_id = -1
            end
			if tableobj.delete_table_timer_id > 0 then
				timer.cleartimer(tableobj.delete_table_timer_id)
				tableobj.delete_table_timer_id = -1
			end
			if tableobj.delete_table_timer_id == -1 then
                tableobj.delete_table_timer_id = 0
                tableobj.delete_table_timer_id = timer.settimer(100, "delete_table")
            end
		end
	else    --未开始，直接删除
		if tableobj.sitdown_player_num <= 0 and tableobj.cur_watch_playernum <= 0 then
            --删除定时器
            if tableobj.timer_id and tableobj.timer_id > 0 then
                timer.cleartimer(tableobj.timer_id)
                tableobj.timer_id = -1
            end
			if tableobj.delete_table_timer_id > 0 then
				timer.cleartimer(tableobj.delete_table_timer_id)
				tableobj.delete_table_timer_id = -1
			end
			if tableobj.delete_table_timer_id == -1 then
                tableobj.delete_table_timer_id = 0
                tableobj.delete_table_timer_id = timer.settimer(100, "delete_table")
            end
		end
	end
end

--
-- 被动站起
--
function TableLogic.passive_standuptable(tableobj, request, seat, reason, is_sendto_client)
	tableobj.sitdown_player_num = tableobj.sitdown_player_num - 1 
	local standuptablemsg = {
		rid = seat.rid,
		seat_index = seat.index,
		table_index = tableobj.index,
        reason = reason,
	}

    --通知客户端
	TableLogic.sendmsg_to_alltableplayer(tableobj, "standuptableN", standuptablemsg)
	seat.state = ELHJSeatState.SEAT_STATE_NO_PLAYER

    --保存进旁观列表
	if tableobj.waits[seat.rid] == nil then
		local waitinfo = {
			playerinfo = {},
		}
		tableobj.waits[seat.rid] = waitinfo
		waitinfo.rid = seat.rid
        waitinfo.playerinfo.coin = seat.playerinfo.coin
        waitinfo.playerinfo.diamond = seat.playerinfo.diamond
        waitinfo.is_robot = seat.is_robot
		tableobj.cur_watch_playernum = tableobj.cur_watch_playernum + 1
	end

	---
	--初始化座位数据
	gamelogic.standup_clear_seat(tableobj.gameobj, seat)
end

--
-- 主动站起
--
function TableLogic.standuptable(tableobj, request, seat)
	tableobj.sitdown_player_num = tableobj.sitdown_player_num - 1
	local noticemsg = {
		rid = seat.rid, 
		seat_index = seat.index,
		table_index = tableobj.index,
		reason = EStandupReason.STANDUP_REASON_ONSTANDUP,
	}

	if tableobj.state == ELHJTableState.TABLE_STATE_UNKNOW then
		TableLogic.sendmsg_to_tableplayer(seat.rid, "standuptableN", noticemsg)
	else
		TableLogic.sendmsg_to_alltableplayer(tableobj, "standuptableN", noticemsg)
	end

	seat.state = ELHJSeatState.SEAT_STATE_NO_PLAYER
	if tableobj.waits[seat.rid] == nil then
		local waitinfo = {
			playerinfo = {},
		}
		tableobj.waits[seat.rid] = waitinfo
		waitinfo.rid = seat.rid
        waitinfo.playerinfo.coin = seat.playerinfo.coin
        waitinfo.playerinfo.diamond = seat.playerinfo.diamond
        waitinfo.is_robot = seat.is_robot
		tableobj.cur_watch_playernum = tableobj.cur_watch_playernum + 1
	end

	--初始化座位数据
	gamelogic.standup_clear_seat(tableobj.gameobj, seat)
end

--
--  所有玩家离桌
--
function TableLogic.leavetableallplayer(tableobj,reason)
    if type(tableobj.seats) ~= "table" then
        return
    end

	for _, seat in pairs(tableobj.seats) do
		if not seatlogic.is_empty(seat) then
            local rid,coin = seat.rid,TableLogic.get_curmoney(seat)
			TableLogic.passive_standuptable(tableobj, nil, seat, reason)
			TableLogic.passive_leavetable(tableobj,rid,coin)
		end
	end
end

--- 断线重连处理函数
-- @param tableobj
-- @param request
-- @param seat
--
function TableLogic.reentertable(tableobj, request, seat)
	local noticemsg
	local player_action
	local tmpseat
    local cur_player_action

    --更改断线状态
    if seat.is_disconnected then
	    seat.is_disconnected = false
    end

    --清除断线计时器
    if seat.disconnect_timer_id > 0 then
        timer.cleartimer(seat.disconnect_timer_id)
        seat.disconnect_timer_id = -1
    end

    --更改离开状态，通知所有玩家
	if seat.is_leave then
		seat.is_leave = false
		local noticemsg = {
			rid = seat.rid,
			seat_index = seat.index,	
		}
		TableLogic.sendmsg_to_tableplayer(seat.rid,"reentertableN", noticemsg)
	end

    --等待准备,则发送准备
	if tableobj.state == ELHJTableState.TABLE_STATE_WAIT_ALL_READY 
		and seat.state == ELHJSeatState.SEAT_STATE_WAIT_READY then
        --TableLogic.sendmsg_to_tableplayer(seat.rid, "doreadyN", {action_timeout_time = seat.ready_timeout_time})
	end
end

--------------------------------------------
--send方法
--

--
-- 通知桌上所有玩家
--
function TableLogic.sendmsg_to_alltableplayer( tableobj, msgname, message)
    local retcode,retstr,msgbody
    if message and message.retcode  then
		retcode = tonumber(message.retcode)
		retstr = message.retstr or ""
		msgbody = message.msgbody or { }
    else
        msgbody = message
	end

    local rids = { }
    local seats = tableobj.seats
    for i,seat in pairs(seats) do
       if not seatlogic.is_empty(seat) 
       and not seat.is_disconnected 
       and not seat.is_robot then
            table.insert(rids,seat.rid)
       end 
    end

    if tableobj.waits ~= nil then
        for i,wait in pairs(tableobj.waits) do
            if not wait.is_robot then
                table.insert(rids,wait.rid)
            end
        end
    end
    
    service:send_notice_to_players(rids, msgname, msgbody, retcode, retstr)
end

--
-- 通知桌上除某玩家之外的所有玩家
-- rid 排除的玩家
--
function TableLogic.sendmsg_to_otheralltableplayer( tableobj,rid, msgname, message)
    local retcode,retstr,msgbody
    if message and message.retcode  then
		retcode = tonumber(message.retcode)
		retstr = message.retstr or ""
		msgbody = message.msgbody or { }
    else
        msgbody = message
	end

    local rids = { }
    local seats = tableobj.seats
    for i,seat in pairs(seats) do
       if not seatlogic.is_empty(seat) and seat.rid ~= rid and 
       not seat.is_disconnected and not seat.is_robot then
            table.insert(rids,seat.rid)
       end 
    end

     if tableobj.waits ~= nil then
        for i,wait in pairs(tableobj.waits) do
            if wait.rid ~= rid and not wait.is_robot then
                table.insert(rids,wait.rid)
            end
        end
    end
    
    service:send_notice_to_players(rids, msgname, msgbody, retcode, retstr)
end

--
-- 通知桌上某个玩家
--
function TableLogic.sendmsg_to_tableplayer( rid, msgname, message)
    local seat = TableLogic.get_seat_by_rid(service.table_data,rid) or {}
    if seat.is_disconnected or seat.is_robot then
        return
    end

    local retcode,retstr,msgbody
    if message and message.retcode  then
		retcode = tonumber(message.retcode)
		retstr = message.retstr or ""
		msgbody = message.msgbody or { }
    else
        msgbody = message
	end

    local rids = { }
    table.insert(rids,rid) 
    service:send_notice_to_players(rids, msgname, msgbody, retcode, retstr)
end

--
-- 通知所有旁观列表玩家
--

function TableLogic.sendmsg_to_allwaitplayer(tableobj, msgname, message)
    local retcode,retstr,msgbody
    if message and message.retcode  then
		retcode = tonumber(message.retcode)
		retstr = message.retstr or ""
		msgbody = message.msgbody or { }
    else
        msgbody = message
	end

    local rids = { }
    local waits = tableobj.waits
    for i,wait in pairs(waits) do
       if wait.rid and not wait.is_robot then
            table.insert(rids,wait.rid)
       end 
    end
    
    service:send_notice_to_players(rids, msgname, msgbody, retcode, retstr)
end

--
-- 更新桌子心跳时间
--
function TableLogic.update_table_heart_time(tableobj)
    tableobj.last_heart_time = timetool.get_time()
end

--
-- 设置所有座位状态
--
function TableLogic.setallseatstate(tableobj, state)
	for k,value in pairs(tableobj.seats) do
		value.state = state
	end
end


--------------------------------------------
--金钱相关

--
-- 结算后钻石信息，每局结算都要通知gate
-- rid_value {beginvalue,value,endvalue,rolename}
--
function TableLogic.game_balance_diamond(rid_values)
    local comment = TableLogic.create_comment()
    local status,result = skynet.pcall(cluster.call,"gatenode", ".router", "brgame_balance_diamond", rid_values, comment)
    if not status then
        filelog.sys_error("game_balance_diamond call failed!")
        return false
    else
        --记录流水日志
        local total_bet = 0
        local total_water = 0
        local sys_change = 0
        local total_change = 0
        for rid,item in pairs(rid_values) do
            total_water = total_water + math.abs(item.real_water or item.real_change or 0)
            total_bet = total_bet + (item.total_bet or 0)
            sys_change = sys_change + item.real_change
            total_change = total_change + item.value

            --记录下注值
            local bet_logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", EDiamondChange.DOBET, rid, item.level, 
            item.total_bet, 0, 0, 0, 0, 0, comment.table_uuid, comment.start_time, comment.table_tradeid)
            skynet.send(".diamondlog", "lua", "write", bet_logstr)
            --记录流水变化值
            local real_water = item.real_water or item.real_change or 0
            local chg_logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", EDiamondChange.FUWUFEI, rid, item.level, real_water, 
            item.beginvalue,item.endvalue, 0, 0, 0, comment.table_uuid, comment.start_time, comment.table_tradeid)
            if real_water ~= 0 then
                skynet.send(".diamondlog", "lua", "write_file_redis", chg_logstr, rid)
            else
                skynet.send(".diamondlog", "lua", "write", chg_logstr)
            end
        end
        --记录系统的流水变化
        local logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", EDiamondChange.FUWUFEI, 0, 0, -sys_change, 0, 0, 0, 0, 0,
        comment.table_uuid, comment.start_time, comment.table_tradeid)
        skynet.send(".diamondlog", "lua", "write", logstr)

        --更新收益值,库存值，扣除抽水
        local tableobj = service.table_data
        local gamename =  TableLogic.get_gamename(tableobj)
        skynet.call(".slotmgr", "lua", "handle_balance_result", gamename, total_change, total_water, total_bet, comment)
    end
    return result,comment
end

--
--  改变金钱
--
function TableLogic.change_money(rid, itemvalues)
    local comment = TableLogic.create_comment()
    local status,result = skynet.pcall(cluster.call,"gatenode", ".router", "change_money", rid, itemvalues, comment)
    if not status then
        filelog.sys_error("change_money call failed!")
        return false
    end
    return result,comment
end

--------------------------------------------
--get方法
--

--
--根据rid获得座位对象
--
function TableLogic.get_seat_by_rid(tableobj, rid)
	if tableobj.seats == nil then
		return nil
	end

	for index, seat in pairs(tableobj.seats) do
		if rid == seat.rid then
			return seat
		end
	end
	return nil
end

--- 根据玩家的rid查找玩家是否在旁观队列
-- @param tableobj 牌桌对象
-- @param rid  玩家rid
function TableLogic.get_waitplayer_by_rid(tableobj, rid)
	for index, waitplayer in pairs(tableobj.waits) do
		if rid == waitplayer.rid then
			return waitplayer
		end
	end
	return nil
end

--
--- 根据指定桌位号获得一张空座位
-- @param tableobj 牌桌对象
-- @param index 座位号
function TableLogic.get_emptyseat_by_index(tableobj, index)
	if index == nil or index <= 0 or index > tableobj.conf.max_player_num then
		for index, seat in pairs(tableobj.seats) do
			if seatlogic.is_empty(seat) then
				return seat
			end
		end
	else
		local seat = tableobj.seats[index]
		if seatlogic.is_empty(seat) then
			return seat
		end
	end
	return nil
end

--
-- 获得桌子索引号
--
function TableLogic.get_table_index(tableobj)
	return tableobj.table_index
end

--
-- 获得坐下玩家数
--
function TableLogic.get_sitdown_player_num(tableobj)
	return tableobj.sitdown_player_num
end

--
-- 获得游戏中玩家数
--
function TableLogic.get_ingame_playernum(tableobj)
	local playernum = 0	
	for _, seat in pairs(tableobj.seats) do
		if gamelogic.is_ingame(tableobj.gameobj, seat) then
			playernum = playernum + 1
		end
	end
	return playernum
end

--------------------------------------------
--is方法
--

--- 判断当前桌子是否坐满
-- @param tableobj  牌桌对象
--
function TableLogic.is_full(tableobj)
	return (tableobj.sitdown_player_num >= tableobj.conf.max_player_num)
end

---判断当前是否能够开始游戏
-- @param tableobj	牌桌对象
--
function TableLogic.is_canstartgame(tableobj)
	return (tableobj.sitdown_player_num >= tableobj.conf.max_player_num)
end

--- 判断游戏是否结束
-- @param tableobj 牌桌对象
--
function TableLogic.is_gameend(tableobj)
	if tableobj.state == ELHJTableState.TABLE_STATE_GAME_END
	or tableobj.state == ELHJTableState.TABLE_STATE_WAIT_PLAYER_SITDOWN
	or tableobj.state == ELHJTableState.TABLE_STATE_UNKNOW then
		return true
	end

	return false
end

--- 判断当前局是否已经结束游戏
-- @param tableobj 牌桌对象
--
function TableLogic.is_onegameend(tableobj)
	if tableobj.state == ELHJTableState.TABLE_STATE_ONE_GAME_REAL_END
	or tableobj.state == ELHJTableState.TABLE_STATE_WAIT_ALL_READY 
    or tableobj.state == ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_START then
		return true
	end

	if not tableobj.is_ingame then
		return true
	end

	return TableLogic.is_gameend(tableobj)
end

--------------------------------------------
--copy方法
--

--
-- 这是要按照proto来组织，然后返回给客户端
--
function TableLogic.copy_table_gameinfo()
    local table_data = service.table_data
	local gameinfo = {}
	gameinfo.table_baseinfo = {}
	gameinfo.table_conf = tabletool.deepcopy(table_data.conf)
	gameinfo.seat_roleinfos = {}
	gameinfo.seat_gameinfos = {}

	gameinfo.table_baseinfo.uuid = table_data.uuid 
	gameinfo.table_baseinfo.index = table_data.index 
	gameinfo.table_baseinfo.code = table_data.code 
	gameinfo.table_baseinfo.state = table_data.state 
	gameinfo.table_baseinfo.create_rid = table_data.create_rid 
	gameinfo.table_baseinfo.create_rolename = table_data.create_rolename 
	gameinfo.table_baseinfo.create_time = table_data.create_time 
	gameinfo.table_baseinfo.sitdown_player_num = table_data.sitdown_player_num 
	gameinfo.table_baseinfo.curr_to_num = table_data.curr_to_num
    gameinfo.table_baseinfo.cur_jackpot_money = table_data.cur_jackpot_money
    gameinfo.table_baseinfo.open_jackpot_timestamp = table_data.open_jackpot_timestamp
    gameinfo.table_baseinfo.init_picture_list = table_data.init_picture_list

	for index,seat in pairs(table_data.seats) do
		gameinfo.seat_roleinfos[index] = TableLogic.copy_seat_roleinfo(seat)
		gameinfo.seat_gameinfos[index] = TableLogic.copy_seat_gameinfo(seat)
	end
	return gameinfo
end


--
--拷贝座位游戏信息
--
function TableLogic.copy_seat_gameinfo(seat)
    local seat_gameinfo ={}
    seat_gameinfo.rid		= seat.rid
    seat_gameinfo.index		= seat.index
    seat_gameinfo.state		= seat.state
    seat_gameinfo.offline	= (seat.is_disconnected and 1) or 0
    seat_gameinfo.cur_money	= TableLogic.get_curmoney(seat)
    seat_gameinfo.cur_total_bet = seat.cur_total_bet
    seat_gameinfo.cur_base_score	= seat.cur_base_score
    seat_gameinfo.cur_multi_num	= seat.cur_multi_num
    seat_gameinfo.cur_line_num	= seat.cur_line_num
    seat_gameinfo.total_score = seat.total_score

    return seat_gameinfo
end

--
--拷贝座位角色信息
--
function TableLogic.copy_seat_roleinfo(seat)
    local seat_roleinfo = {}
    seat_roleinfo.rid = seat.rid
    seat_roleinfo.rolename = seat.playerinfo.rolename
    seat_roleinfo.logo = seat.playerinfo.logo
    seat_roleinfo.sex = seat.playerinfo.sex
    seat_roleinfo.coin = seat.playerinfo.coin
    seat_roleinfo.diamond = seat.playerinfo.diamond
    seat_roleinfo.intro = seat.playerinfo.intro
    seat_roleinfo.ip_addr = seat.playerinfo.ip_addr
    seat_roleinfo.gps_addr = seat.playerinfo.gps_addr
    seat_roleinfo.upvoted_num = seat.playerinfo.upvoted_num
    seat_roleinfo.downvoted_num = seat.playerinfo.downvoted_num
    seat_roleinfo.logoframe = seat.playerinfo.logoframe
    return seat_roleinfo
end

------------------------------------------------
--其他

--清空桌子对象数据
--
function TableLogic.clear(tableobj)
	if tableobj.timer_id > 0 then
		timer.cleartimer(tableobj.timer_id)
		tableobj.timer_id = -1
	end

	if tableobj.delete_table_timer_id > 0 then
		timer.cleartimer(tableobj.delete_table_timer_id)
		tableobj.delete_table_timer_id = -1
	end

	for k,v in pairs(tableobj) do
		tableobj[k] = nil
	end
end

--
--创建comment
--
function  TableLogic.create_comment()
    local tableobj = service.table_data
    local tradeid = skynet.call(".nodeuuid", "lua", "getuuid")
    local start_time = tableobj.one_start_time or 0
   
    return {table_uuid = tableobj.uuid ,table_tradeid = tradeid,start_time = start_time,jackpot_id = tableobj.cur_jackpot_id}
end

--
--断开连接(断线）
--
function TableLogic.disconnect(tableobj, request, seat)
	seat.is_disconnected = true
	seat.is_leave = true
	local noticemsg = {
		rid = seat.rid,
		seat_index = seat.index,	
	}

	TableLogic.sendmsg_to_alltableplayer(tableobj,"disconnectN", noticemsg)

    --停止自动开始
    if tableobj.is_auto_start then
        tableobj.is_auto_start = false
    end

    --断线60s后，将其踢出
    if seat.disconnect_timer_id == -1 then
        seat.disconnect_timer_id = 0
        seat.disconnect_timer_id = timer.settimer(60 * 100, "disconnect_outtime", {index = seat.index})
    end

    --准备断线，将其踢出桌子
    if tableobj.state == ELHJTableState.TABLE_STATE_WAIT_ALL_READY 
    and seat.state == ELHJSeatState.SEAT_STATE_WAIT_READY then
        local rid,coin = seat.rid,TableLogic.get_curmoney(coin)
        TableLogic.passive_standuptable(tableobj, {}, seat, EStandupReason.STANDUP_REASON_DISCONNECTED)	
        TableLogic.passive_leavetable(tableobj,rid,coin)
    end
    
    --比倍中，则立即结束
    if tableobj.is_wait_comp_multi or tableobj.is_compare_multiing then
        tableobj.is_wait_comp_multi = nil
        tableobj.is_compare_multiing = nil
        
        --取消定时器
        if tableobj.timer_id > 0 then
            timer.cleartimer(tableobj.timer_id)
            tableobj.timer_id = -1
        end
        
        --结束游戏
        tableobj.state = ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_END
        local timer_id = timer.settimer(5, "onegameend")	
        if tableobj.state ~= ELHJTableState.TABLE_STATE_WAIT_ONE_GAME_END then
            timer.cleartimer(timer_id)
        else
            tableobj.timer_id = timer_id
        end
    end
    
end

------------------------------------------------------------------------
------------------------------------------------------------------------

--- 保存牌桌每局记录
-- @param game_records 游戏记录
--
function TableLogic.save_table_records(game_records)
    if not game_records.user_count or game_records.user_count <= 0 then
        return
    end

    local tablerecords = {}

    tablerecords.user_count = game_records.user_count                       --游戏总人数
    tablerecords.sys_diamond_start = game_records.sys_diamond_start         --系统开始元宝
    tablerecords.sys_diamond_end = game_records.sys_diamond_end             --系统结束元宝
    tablerecords.begin_time = game_records.one_start_time                   --本局开始时间
    tablerecords.end_time = game_records.one_end_time                       --本局结束时间
    tablerecords.game_type = skynet.getenv("nodename")                      --游戏类型
    tablerecords.room_num = game_records.table_code                         --房间号
    tablerecords.game_info = game_records.players_balance_list              --玩家结算信息
    tablerecords.init_picture_list = game_records.init_picture_list         --开始图标
    tablerecords.result_picture_list = game_records.result_picture_list     --结束图标
    tablerecords.spin_result = game_records.spin_result                     --中奖结果
    tablerecords = json.encode(tablerecords)

    --调用日志服务写到文件
	skynet.send(".tablerecordlog", "lua", "write",game_records.cur_record_id,tablerecords)
end

--- 保存牌桌最终记录(桌子被删除时）
-- @param tableobj 桌子对象
--
function TableLogic.save_table_final_records(tableobj)
    local game_records = tableobj.game_records

    local tablerecords = ""
	tablerecords = tablerecords .. game_records.table_uuid .. "_"           --桌子唯一id
    tablerecords = tablerecords .. game_records.table_type .. "_"           --桌子类型
	tablerecords = tablerecords .. game_records.create_user_rid .. "_"      --创建者rid
	tablerecords = tablerecords .. game_records.create_time .. "_"          --创建时间
    tablerecords = tablerecords .. game_records.delete_time .. "_"          --删除时间
	tablerecords = tablerecords .. game_records.start_time .. "_"           --第一局开始时间
    tablerecords = tablerecords .. game_records.end_time .. "_"             --最后一局结束时间
    tablerecords = tablerecords .. game_records.final_to_num .. "_"         --最终局数
    tablerecords = tablerecords .. game_records.delete_reason or 0          --删除原因
    
    --调用日志服务写到文件
	skynet.send(".gametablelog", "lua", "write",tablerecords)
end



--
--获取游戏名（包括桌子类型)
--
function TableLogic.get_gamename(tableobj)
    local gamename = "lhj"
    if tableobj.table_type == ELHJTableType.TABLE_TYPE_COIN then
        gamename = gamename .. "_coin"
    elseif tableobj.table_type == ELHJTableType.TABLE_TYPE_DIAMOND then
        gamename = gamename .. "_diamond"
    end
    return gamename
end

--
--获得当前代币数
--
function TableLogic.get_curmoney(seat)
    if not seat or not seat.playerinfo then
        return 0
    end

    local tableobj = service.table_data
    if tableobj.table_type == ELHJTableType.TABLE_TYPE_DIAMOND then
        return (seat.playerinfo.diamond or 0)
    elseif tableobj.table_type == ELHJTableType.TABLE_TYPE_COIN then
        return (seat.playerinfo.coin or 0)
    end
    return 0
end

--
--是否是金币桌
--
function TableLogic.is_cointable()
    if service.table_data.table_type == ELHJTableType.TABLE_TYPE_COIN then
        return true
    end
    return false
end

--
--是否是钻石桌
--
function TableLogic.is_diamondtable()
    if service.table_data.table_type == ELHJTableType.TABLE_TYPE_DIAMOND then
        return true
    end
    return false
end

--
--发送跑马灯
--
function TableLogic.send_horseracelamp(rolename, get_num)
	local horseconf = configdao.get_common_conf("horselampconf")
	if not horseconf or not horseconf[1] then return end
	local formatname = string.format(ELAMPCOLOR.GREEN, rolename)
	local formatnum = string.format(ELAMPCOLOR.RED, tostring(get_num))
	local horsestring = string.format(horseconf[1], formatname, EGameName, formatnum)
	skynet.pcall(cluster.send, "gatenode", ".router", "addpopmessage", horsestring)
end

return TableLogic